<?php
namespace app\common\controller;
use app\common\model\Setup as SetupModel;
use app\common\model\User as UserModel;
use app\common\model\ProjectClassify as ProjectClassifyModel;

use app\api\controller\Weixin;
use org\Auth;
use think\Loader;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Session;

/**
 * 前台公用基础控制器
 * Class WapBase
 * @package app\common\controller
 */
class WapBase extends Controller
{
    protected $setup_model;
    protected $user_model;
    protected $project_classify_model;
    protected function _initialize()
    {
        parent::_initialize();
        $this->setup_model                    = new SetupModel();
        $this->user_model                     = new UserModel();
        $this->project_classify_model         = new ProjectClassifyModel();

        if(!$this->is_mobile()){
            //$this->redirect('index/index/index');
        }

        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            session('scope' , $this->request->param('scope' , null));
            if(!session('openid')) {
                $code = $this->request->param('code' , null);
                $state = $this->request->param('state' , null);
                if( $code && $state === cookie('state') ) {
                    $this->getInfo();
                }
                else {
                    $this->redir();
                }
            }
        }
        $this->getSetup();
        $this->getUser();

        // 输出当前请求控制器（配合后台侧边菜单选中状态）
        $this->assign('controller', Loader::parseName($this->request->controller()));
    }

    /**
     * 获取预约项目菜单
     */
    protected function getSetup()
    {
        $setup   = $this->setup_model->find(1);
        $this->assign('setup', $setup);
    }

    /**
     * 获取登录管理员信息
     */
    protected function getUser()
    {
        //账号openid识别
        if(Session('openid')){
            $index_user = $this->user_model->where('openid',Session('openid'))->find();
            if($index_user){
                Session::set('index_id',$index_user['id']);
            }else{
                Session::delete('openid');
            }
        }
        //账号非openid识别
        $index_user = [];
        if(Session('index_id')){
            $index_user = $this->user_model->find(Session('index_id'));
            if($index_user){
                Session::set('index_id',$index_user['id']);
            }else{
                Session::delete('index_id');
            }
        }
        $this->assign('index_user', $index_user);
    }

    //oauth跳转
    private function redir()
    {
        $url = $this->request->url(true);
        cookie('state' , rand(100000 , 999999));
        $Weixin = new Weixin();
        $scope = 'snsapi_userinfo';//授权
        $result = $Weixin->get_oauth_redirect($url , cookie('state') , $scope);
        $this->redirect($result);
    }

    /**
     * 获取用户信息
     * @author zlbao<276363733@QQ.com>
     * @date   : 2018/7/7/007
     */
    private function getInfo()
    {
        $Weixin = new Weixin();
        $result = $Weixin->get_oauth_accesstoken();
        //var_dump($result);
        if( $result['access_token'] && $result['openid'] ) {
            //获取用户信息
            $info = $Weixin->get_user_info($result['access_token'] , $result['openid'] , 'zh_CN');
            if (isset($info['openid'])==false) {
                die('获取用户信息失败');
            }else{
                //创建用户
                $openid = $info['openid'];
                $user_see = $this->user_model->where(['openid'=>$openid])->find();
                if(!$user_see){
                    $user_data['openid']      = $info['openid'];
                    $user_data['name']        = $this->replace_emoji($info['nickname']);
                    $user_data['img']         = $info['headimgurl'];
                    $user_data['sex']         = $info['sex'];
                    $user_data['province']    = $info['province'];
                    $user_data['city']        = $info['city'];
                    $this->user_model->save($user_data);
                }
                session('openid' , $info['openid']);
            }
            $this->_url_replace();
        }
        else {
            echo('授权失败，重新授权！');
            $this->_url_replace();
        }
    }

    /** 将微信网页授权后的参数剔除掉 */
    function _url_replace()
    {
        if( $this->request->param('code') && $this->request->param('state') ) {
            $url = $this->request->url(true);
            $reg = '/\?code.*&state.*$/';
            $url = preg_replace($reg , '' , $url);
            $this->redirect($url);
        }
    }

    //文字特殊符号处理
    function replace_emoji($str){
        return preg_replace_callback('/[\xf0-\xf7].{3}/', function($r) { return '@E' . base64_encode($r[0]);}, $str);
    }


    //判断电脑还是手机访问
    function is_mobile(){
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
        {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT']))
        {
            $clientkeywords = array ('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT']))
        {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                return true;
            }
        }
        return false;
    }


}